package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName TrackReceiver
 * @description: TODO
 * @date 2023年11月03日
 * @version: 1.0
 */
@Component
@Slf4j
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void trackStatUpdate(ConsumerRecord<String, String> record) {
        //  获取数据
        String strJson = record.value();
        if (StringUtils.isEmpty(strJson)) return;
        //  声明对象数据类型转换
        TrackStatMqVo trackStatMqVo = JSON.parseObject(strJson, TrackStatMqVo.class);
        Assert.notNull(trackStatMqVo,"这个对象为空");
        //  判断数据是否为空.
        try {
            //  获取到业务编号
            String businessNo = trackStatMqVo.getBusinessNo();
            //  借助redis
            Boolean result = redisTemplate.opsForValue().setIfAbsent(businessNo, businessNo, 24, TimeUnit.HOURS);
            //  判断这个key是否存在. result=true; 没有.
            if (result) {
                //  调用服务层方法，更新声音，专辑播放量 track_id stat_type stat_num, count
                trackInfoService.updateStat(trackStatMqVo.getAlbumId(), trackStatMqVo.getTrackId(), trackStatMqVo.getStatType(), trackStatMqVo.getCount());
            }
        }catch (Exception e){
            log.error("消费异常{}",trackStatMqVo.getTrackId());
            //  删除数据
            this.redisTemplate.delete(trackStatMqVo.getBusinessNo());
        }
    }

}
